package jp.oesf.malfoy.rss;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class RssService extends Service {

    private final String TAG = "RssService";

	private String xml = null;
	private IRssService.Stub binder = new IRssService.Stub() {

		public String getXml() throws RemoteException {
			Log.v(TAG, "getXml()");
			return xml;
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Log.v(TAG, "onStart");
		Log.v(TAG, "RssTask.execute()");
		String url = intent.getStringExtra(RssConst.RSS_SERVICE_TAG);
		//if (url == null || url.isEmpty()){
		//	Toast.makeText(getApplicationContext(), RssConst.RSS_NO_URL, Toast.LENGTH_LONG).show();
		//}else {
			new RssTask().execute(url);
		//}
	}

	@Override
	public void onDestroy() {
		Log.v(TAG, "onDestroy");
	}

	class RssTask extends AsyncTask<String, Integer, String> {

	    private final String TAG = "RssService";

		@Override
		protected String doInBackground(String... params) {
			Log.v(TAG, "doInBackground()");

			String data = "";
			String message = "";
			String url = params[0];

			if (url == null || url.isEmpty()){
				message = RssConst.RSS_NO_URL;
				data = "";
			} else {
				HttpResponse res = getConnection(url);
				if (res == null){
					message = RssConst.RSS_NO_RESPONSE;
					data = "";
				} else {
					data = getContents(res);
					if (data == null){
						message = RssConst.RSS_NO_RESPONSEDATA;
						data = "";
					}
				}
			}

			if (!message.isEmpty()){
				// サービスからのブロードキャストの送信
				Log.v(TAG, "sendBroadcast()");
			    Intent intent = new Intent();
			    intent.putExtra(RssConst.RSS_RECEIVER_TAG, message);
			    intent.setAction(RssConst.RSS_MSG_ACTION);
			    sendBroadcast(intent);
			}

			return data;
		}

		@Override
		protected void onPostExecute(String result) {
			Log.v(TAG, "onPostExecute()");
	        xml = result;
		}

	    private HttpResponse getConnection(String url){

	    	try {
	        	DefaultHttpClient client = new DefaultHttpClient();
	        	HttpGet get = new HttpGet(url);
				HttpResponse res =client.execute(get);

				if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
					return res;
				} else {
					Log.e(TAG, "status code : " + res.getStatusLine().getStatusCode());
				}
			} catch (Exception e) {
				Log.e(TAG, Log.getStackTraceString(e));
			}

			return null;
	    }

	    private String getContents(HttpResponse res){

	    	InputStream in = null;
	    	ByteArrayOutputStream out =null;
	    	byte[] line = new byte[1024];
	    	String data = "";
	    	int size=0;

	    	try {
				in = res.getEntity().getContent();
				out = new ByteArrayOutputStream();
				for(;;){
					size = in.read(line);
					if (size <0){
						break;
					}
					out.write(line, 0, size);
				}
				data = new String(out.toByteArray(),RssConst.RSS_ENCODE);
			} catch (Exception e) {
				Log.e(TAG, Log.getStackTraceString(e));

			}finally{
				try {
					if (in != null) {
						in.close();
					}
					if (out != null) {
						out.close();
					}
				} catch (Exception e) {
					Log.e(TAG, Log.getStackTraceString(e));
				}
			}

			return data;
	    }
	}
}